//
//  webMethod.m
//  testassembly
//
//  Created by liangang on 2018/3/25.
//  Copyright © 2018年 liangang. All rights reserved.
//

#import "webMethod.h"
#import "QRScanViewController.h"
#import "ViewController.h"
#import "getResourcesApi.h"
#import "UDIDFaceCompareFactory.h"
#import "detailViewController.h"
#import "getVideoDetailApi.h"
#import "AppDelegate.h"
#import "videoViewController.h"
#import "changeOrderStatusApi.h"
#import "DMContactStore.h"
#import "submitContactsApi.h"
#import "FMFileVideoController.h"
#import "INTULocationManager.h"
 #import <MapKit/MapKit.h>
#import "alipayApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>
#import "WxPayApi.h"
#import "WXApi.h"
@interface webMethod()<QRScanDelegate,UIActionSheetDelegate>
{
    NSString *lat ,*lon;
}

@property(strong,nonatomic)UIViewController *openVC;
@property (nonatomic, strong) DMContactStore *contactsStore;
@end
@implementation webMethod
+ (instancetype)sharedInstance {
    static webMethod *sharedInstance = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });
    
    return sharedInstance;
}
-(void)openScane:(UIViewController *)vcA
{
    QRScanViewController *vc = [[QRScanViewController alloc] init];
    vc.delegate = self;
//    [vcA showViewController:vc sender:nil];
    vc.hidesBottomBarWhenPushed = YES;
    [vcA.navigationController pushViewController:vc animated:YES];
}
- (void)qrScanResult:(NSString *)result viewController:(QRScanViewController *)qrScanVC
{
    NSLog(@"%@",result);
    
     [qrScanVC.navigationController popViewControllerAnimated:NO];
    detailViewController   *vc  =  [[detailViewController    alloc]init];
    vc.url = result;
    vc.hidesBottomBarWhenPushed = YES;
    [self.currentVC.navigationController pushViewController:vc animated:YES];
    
//    if([result containsString:@"lialoan"]||[result containsString:@"suo.im"])
//    {
//         [qrScanVC.navigationController popViewControllerAnimated:NO];
//        detailViewController   *vc  =  [[detailViewController    alloc]init];
//        vc.url = result;
//        vc.hidesBottomBarWhenPushed = YES;
//        [self.currentVC.navigationController pushViewController:vc animated:YES];
//    }
//    else
//    {
//        [qrScanVC.navigationController popViewControllerAnimated:YES];
//        MBProgressHUD *hud = [[MBProgressHUD alloc]initWithWindow:[UIApplication sharedApplication].keyWindow];
//        [[UIApplication sharedApplication].keyWindow addSubview:hud];
//
//
//        //    MBProgressHUD *hud = [MBProgressHUD alloc]
//        hud.mode = MBProgressHUDModeText;
//        [hud setRemoveFromSuperViewOnHide:YES];
//        hud.detailsLabelText = @"扫码失败，请重试";
//        [hud show:YES];
//        [hud hide:YES afterDelay:2.0f];
//    }
}
-(void)FaceAuth:(UIViewController *)VC
{
    self.openVC = VC;
    getResourcesApi *api = [[getResourcesApi alloc]init];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
        
        NSDictionary *dic = request.responseJSONObject;
        
        _engine = [[UDIDEngine alloc] init];
        _engine.delegate = self;
        _engine.actions = @[@1,@2];
        _engine.randomCount = 3;  // 随机个数
        _engine.livingModeSettings = @[@0, @1, @3];
        // 或者 engine.livingModeSettings = @[[NSNumber numberWithUnsignedInteger:UDIDLivingBlink],[NSNumber numberWithUnsignedInteger:UDIDLivingSmile],[NSNumber numberWithUnsignedInteger:UDIDLivingFaceToRight]];
        _engine.livingMode = UDIDLivingCustomMode;  // 枚举活体类型
        _engine.closeRemindVoice = YES;
        /* 通用参数 */
        _engine.pubKey = dic[@"pubKey"];
        _engine.sign = dic[@"sing_str"];
        _engine.signTime = dic[@"sign_time"];
        _engine.partnerOrderId = dic[@"partner_order_id"];
        _engine.notifyUrl = @"";
        UDIDFaceCompareItem *item = [UDIDFaceCompareFactory getByBase64:dic[@"cardid_pic"]];
        _engine.compareItemA  = item;
        [_engine startIdSafeAuthInViewController:VC]; // 开始流程方法
    } failure:^(__kindof YTKBaseRequest *request) {
        
    }];
    
    
   
}
- (void)idSafeEngineFinishedResult:(UDIDEngineResult)result UserInfo:(id)userInfo
{
    
    if (result == UDIDEngineResult_Liveness) {
        UDIDFaceCompareItem *item = [UDIDFaceCompareFactory getByUrl:userInfo[@"living_photo"]];
        _engine.compareItemB = item;
        [_engine startIdSafeAuthInViewController:self.currentVC.navigationController]; // 开始流程方法
    }
   else
   {

       changeOrderStatusApi *api = [[changeOrderStatusApi alloc]init];
       api.argument  = userInfo;
       [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
           NSLog(@"%@",request.responseString);
           NSString *info ;
           if ([request.responseJSONObject[@"similarity"] boolValue]) {
               info = @"操作失败，必须本人操作";
           }
           else
           {
               info = @"报名成功，请前往订单查看订单状态";
           }
           UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息" message:info delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil  , nil];
           [alert show];
       } failure:^(__kindof YTKBaseRequest *request) {
           
       }];
       CYLTabBarController *bar =[AppDelegate creatTabBar];
       [UIApplication sharedApplication].keyWindow.rootViewController =bar;
       [bar setSelectedIndex:3];
   }
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]])
        {
            //        AppDelegate *delegat = [UIApplication sharedApplication].delegate;
            
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%@&lon=%@&dev=0&style=2",@"导航功能",@"nav123456",lat,lon] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        }
        else
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/gao-tu-zhuan-ye-shou-ji-tu/id461703208?mt=8"]];
            
        }
    }
    else if (buttonIndex==1)
    {
        //获取当前位置
        
        MKMapItem *mylocation = [MKMapItem mapItemForCurrentLocation];
        
        
        
        //当前经维度
        
        float currentLatitude=mylocation.placemark.location.coordinate.latitude;
        
        float currentLongitude=mylocation.placemark.location.coordinate.longitude;
        
        
        
        CLLocationCoordinate2D coords1 = CLLocationCoordinate2DMake(currentLatitude,currentLongitude);
        
        
        
        //目的地位置
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([lat floatValue],[lon floatValue]);
//        coordinate.latitude=[  floatValue];
//
//        coordinate.longitude=[[dataSource objectForKey:@"lng"] floatValue];
//
        
        
        
        
        CLLocationCoordinate2D coords2 = coordinate;
        
        
        
        // ios6以下，调用google map
        
       
            
            //当前的位置
            
            MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
            
            //起点
            
//            MKMapItem *currentLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coords1 addressDictionary:nil]];
        
            //目的地的位置
            
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coords2 addressDictionary:nil]];
            
            
            
            toLocation.name = @"目的地";
            
//            NSString *myname=[dataSource objectForKey:@"name"];
//
//            if (![XtomFunction xfunc_check_strEmpty:myname])
//
//            {
//
//                toLocation.name =myname;
//
//            }
        
            
            
            NSArray *items = [NSArray arrayWithObjects:currentLocation, toLocation, nil];
            
            NSDictionary *options = @{ MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsMapTypeKey: [NSNumber numberWithInteger:MKMapTypeStandard], MKLaunchOptionsShowsTrafficKey:@YES };
            
            //打开苹果自身地图应用，并呈现特定的item
            
            [MKMapItem openMapsWithItems:items launchOptions:options];
        
    }
}
-(void)Contacts
{
    DMContactStore *store = [[DMContactStore alloc]init];
    NSMutableArray *array = [[NSMutableArray alloc]init];
    [store callContactStoreGetAllHandler:^(NSArray *contactStoreModels) {
        
        for (DMContactStoreModel *model in contactStoreModels) {
            NSLog(@"%@",model);
            NSDictionary *dic = @{@"name":model.name,@"mobile":model.phoneNumber};
            [array addObject:dic];
        }
        submitContactsApi *api = [[submitContactsApi alloc]init];
        api.argument     = array;
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
            NSLog(@"%@",request.responseString);
        } failure:^(__kindof YTKBaseRequest *request) {
            NSLog(@"%@",request.responseString);
        }];
    } unAuthorizedBlock:^{
        
    }];
    
}
-(void)Video
{
    FMFileVideoController *vc = [[FMFileVideoController alloc]init];
    [self.currentVC.navigationController    pushViewController:vc animated:YES];
}
-(void)shareAction
{
    
}
-(void)alipayWithOrderNumber:(NSString *)orderNum
{
    alipayApi    *api  =[[alipayApi alloc]init];
    api.order_no = orderNum ;
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
        NSLog(@"%@",request.responseString);
        [[AlipaySDK  defaultService] payOrder:request.responseJSONObject[@"data"] fromScheme:@"ddxueche" callback:^(NSDictionary *resultDic) {
             NSLog(@"reslut = %@",resultDic);
        }];
    } failure:^(__kindof YTKBaseRequest *request) {
        
    }];
}
-(void)WxPayActionWithOrder:(NSString *)orderNum
{
    WxPayApi   *api =[[WxPayApi alloc]init];
    api.order_no = orderNum;
    [api    startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
        NSLog(@"%@",request.responseString);
        if ([request.responseJSONObject[@"error"] integerValue]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"消息" message:request.responseJSONObject[@"error"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            
        }
        else
        {
            NSDictionary *dic = request.responseJSONObject;
            PayReq *pay = [[PayReq alloc]init];
            pay.partnerId = dic[@"partnerid"];
            pay.prepayId = [dic objectForKey:@"prepayid"];
//            prepay_id =[dic objectForKey:@"prepay_id"];
            pay.nonceStr = [dic objectForKey:@"noncestr"];
//            nonceStr =[dic objectForKey:@"nonceStr"];
            pay.timeStamp = (UInt32)[[dic objectForKey:@"timestamp"] intValue];
            pay.package =[dic objectForKey:@"package"];
            pay.sign = [dic objectForKey:@"sign"];
//            sign =[dic objectForKey:@"sign"];
            [WXApi sendReq:pay];
        }
    } failure:^(__kindof YTKBaseRequest *request) {
        NSLog(@"%@",request.responseString);
    }];
    
}

-(void)shareAction:(NSDictionary *)dic WithType:(ShareType)type
{
    SSDKPlatformType agentTpye ;
    if (type==WX) {
        agentTpye = SSDKPlatformSubTypeWechatSession;
    }
   else if (type==WXPY) {
         agentTpye = SSDKPlatformSubTypeWechatTimeline;
    }
    else{
         agentTpye = SSDKPlatformSubTypeQQFriend;
    }
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:dic[@"title"]
                                     images:@[[UIImage imageNamed:@"logo1"]]
                                        url:dic[@"url"]
                                      title:dic[@"title"]
                                       type:SSDKContentTypeAuto];
    [ShareSDK share:agentTpye parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        NSLog(@"%@",error.description);
    }];
    
    
}
-(void)goToNavLat:(NSString *)_lat WithLon:(NSString *)_lon
{
    
    lat = _lat;
    lon = _lon;
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选择地图" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil  otherButtonTitles:@"高德地图",@"苹果地图", nil];
    [sheet showInView:self.currentVC.view];
   
}
//https://www.lialoan.com/DriverApp/?m=video/learn/getVideoDetail&id=2
-(void)PlayVideo:(NSString *)videoId
{
    videoViewController *vc = [[videoViewController alloc]init];
    vc.videoId = videoId;
    vc.hidesBottomBarWhenPushed = YES;
    [self.currentVC.navigationController pushViewController:vc animated:YES];
}
-(UIViewController *)currentVC
{
//    if (!_currentVC) {
        _currentVC =[self topViewController];
//    }
    return _currentVC;
}
- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}
- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

@end
